package net.zrnecko.km;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.zrnecko.km.client.PersistenceService;
import net.zrnecko.km.entity.DataFileProcessor;
import net.zrnecko.km.entity.Tournament;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import com.google.inject.Inject;
import com.google.inject.Singleton;

@SuppressWarnings("serial")
@Singleton
public class UploadServlet extends HttpServlet {

	@Override
	public void init() throws ServletException {
		super.init();
		// Global logging level setting
		log.setLevel(Level.INFO);
		log.info("Initializing UploadServlet...");
	}

	@Inject
	private Logger log;
	
	// TODO will be removed, persistence will be executed in DataFileProcessor
	@Inject
	private PersistenceService ps;
	
	@Inject
	private DataFileProcessor dataFileProcessor;
	
	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		// TODO Auto-generated method stub
		boolean isMultipart = ServletFileUpload.isMultipartContent(req);
		if (isMultipart) {
			// Create a factory for disk-based file items
			FileItemFactory factory = new DiskFileItemFactory();
			// Create a new file upload handler
			ServletFileUpload upload = new ServletFileUpload(factory);
			List<FileItem> items = null;
			// Parse the request
			try {
				/* line 58 */items = upload.parseRequest(req);
				log.info("Request has " + items.size() + " parts.");
				Iterator iter = items.iterator();
				while (iter.hasNext()) {
					FileItem item = (FileItem) iter.next();

					if (item.isFormField()) {
						processFormField(item);
					} else {
						processUploadedFile(item);
					}
				}
				/*
				
				Tournament t = new Tournament();
				t.setDate(new Date());
				ps.persistTournament(t);
				*/

			} catch (FileUploadException except) {
				/* ... */
			}
		}
		resp.setContentType("text/plain");
		PrintWriter out = resp.getWriter();

	}

	private void processUploadedFile(FileItem item) {
		log.log(Level.INFO, "File name: " + item.getName());
		dataFileProcessor.process("Tournament", item);
	}
	
	private void processFormField(FileItem item) {
		log.log(Level.INFO, "Field item name: " + item.getFieldName());
		// TODO Auto-generated method stub
		
	}

	
}
